﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HRProject.Code.Common;
using System.IO;
using HRProject.Code.DTO;
using HRProject.Code.DAO;

namespace HRProject
{
    public partial class UploadFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string fileName = Request.Params["Filename"];
            int lastDot = fileName.LastIndexOf('.');
            lastDot = (lastDot < 0) ? fileName.Length : lastDot;
            fileName = fileName.Insert(lastDot, DateTime.Now.ToString("yyyyMMddHHmmssfff"));

            string category = Request.Params["category"];
            string userId = Request.Params["userId"];
            HttpPostedFile fileData = Request.Files["Filedata"];
            string folder = "/attachment/" + category + "/" + userId;
            string filePath = folder + "/" + fileName;
            string absoluteFolder = Server.MapPath(folder);
            if (!Directory.Exists(absoluteFolder))
            {
                Directory.CreateDirectory(absoluteFolder);
            }
            string absoluteFilePath = Server.MapPath(filePath);
            fileData.SaveAs(absoluteFilePath);
            Console.Out.Write(fileName);

            string generatedName = Path.GetRandomFileName();
            BLDownloadableFile file = new BLDownloadableFile();
            file.SessionId = Session.SessionID;
            file.Url = filePath;
            file.FileName = Request.Params["Filename"];
            file.GeneratedName = generatedName;
            DownloadableFileDAO downloadDao = new DownloadableFileDAO();
            int errorcode = 0;
            downloadDao.Add(file, ref errorcode);

            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write("{\"result\":true,\"dfile\":\""+generatedName+"\"}");
            Response.End();
        }
    }
}
